<script setup lang="ts">
import { storeToRefs } from "pinia";
import { computed, ComputedRef, onMounted, provide, reactive, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { options } from "@/constants";
import type { Ref } from "vue";
import type { Patient } from "@/types/patientTypes";
import type { Router, RouteLocationNormalized } from "vue-router";
import useConsultStore from "@/pinia/modules/consultStore.ts";
import usePatientStore from "@/pinia/modules/patientStore.ts";
import PatientList from "@/views/patient/components/patientList/patientList.vue";
import Add from "@/views/patient/components/Add/Add.vue";
import Tip from "@/views/patient/components/Tip/Tip.vue";
import NavBar from "@/components/lib/NavBar.vue";
import { showFailToast, showSuccessToast } from "vant";
const consultStore = useConsultStore();
const patientStore = usePatientStore();
const router: Router = useRouter();
const route: RouteLocationNormalized = useRoute();
const { patientList, showPopup, edit } = storeToRefs(patientStore);
/*查找患者的请求函数*/
const findPatient = async (patientId: string) => {
    try {
        const { name, idCard, defaultFlag, id, gender } = await patientStore.findPatient(patientId);
        Object.assign(formData, { name, idCard, defaultFlag, id, gender });
    } catch (error: any) {
        showFailToast(error.message);
    }
};
/*是添加患者状态还是选择患者状态(根据路由参数selectPatient来判断)*/
const isSelect = computed<boolean>(() => route.query.selectPatient === "true");
/*使用provide()将数据提供给子组件进行消费*/
provide("findPatient", findPatient);
provide<Ref<Patient[]>>("patientList", patientList);
provide<ComputedRef<boolean>>("isSelect", isSelect);
/*表单数据对象*/
const formData = reactive<Patient>({
    name: "",// 患者姓名
    idCard: "",// 患者身份证号
    defaultFlag: 0,// 是否设置为默认患者
    gender: 1, // 性别
});
const defaultFlag = computed<boolean>({
    get() {
        return formData.defaultFlag === 1;
    },
    set(value) {
        formData.defaultFlag = value ? 1 : 0;
    },
});
/*添加患者标题还是编辑患者标题*/
const title = computed<string>(() => edit.value ? "编辑患者" : "添加患者");
/*添加患者的回调函数*/
const handleAdd = () => {
    patientStore.changeShowPopup(true);
    patientStore.changeEdit(false);
};
/*表单的提交事件*/
const handleSubmit = async () => {
    if (edit.value) {
        try {
            await patientStore.updatePatient(formData);
            await patientStore.fetchPatient();
            patientStore.changeShowPopup(false);
            showSuccessToast("患者更新成功");
        } catch (error: any) {
            showFailToast(error.message);
        }
    } else {
        try {
            delete formData.id;
            await patientStore.addPatient(formData);
            await patientStore.fetchPatient();
            patientStore.changeShowPopup(false);
            showSuccessToast("患者添加成功");
        } catch (error: any) {
            showFailToast(error.message);
        }
    }
};
/*弹层关闭动画结束时候的回调函数*/
const closedPopup = () => {
    Object.assign(formData, {
        name: "",// 患者姓名
        idCard: "",// 患者身份证号
        defaultFlag: 0,// 是否设置为默认患者
        gender: 1, // 性别
    });
};

const patientId = ref<string>("");

/*点击下一步的回调函数*/
const next = () => {
    consultStore.setPatientId(patientId.value);
    router.push("/consult/pay")
};

/*patient-list子组件的自定义事件用于得到患者的ID*/
const getPatientId = (id: string) => {
    patientId.value = id;
};

onMounted(() => {
    patientStore.fetchPatient();
});
</script>

<template>
    <div class="patient">
        <nav-bar left-arrow left-text="返回" :title="isSelect?'选择患者':'家庭档案'" fixed @click-left="$router.back()"></nav-bar>
        <div class="patient-change" v-if="isSelect">
            <h3>请选择患者信息</h3>
            <p>以便医生给出更准确的治疗，信息仅医生可见</p>
        </div>
        <patient-list @getPatientId="getPatientId"></patient-list>
        <add text="添加患者" @click="handleAdd"></add>
        <tip text="最多添加20人"></tip>
        <div class="button" v-if="isSelect">
            <van-button block round type="primary" @click="next">下一步</van-button>
        </div>
        <van-popup v-model:show="showPopup" position="right" :style="{width:'100%',height:'100%'}" @closed="closedPopup">
            <nav-bar :title="title" left-text="返回" left-arrow @click-left="patientStore.changeShowPopup(false)"></nav-bar>
            <van-form label-width="90px" @submit="handleSubmit">
                <van-field label="真实姓名" placeholder="请输入真实姓名" v-model="formData.name" />
                <van-field label="身份证号" placeholder="请输入身份证号" v-model="formData.idCard" />
                <van-field label="性别" class="pb4">
                    <template #input>
                        <radio :options="options" v-model="formData.gender"></radio>
                    </template>
                </van-field>
                <van-field label="默认就诊人">
                    <template #input>
                        <van-switch size="20px" v-model="defaultFlag" />
                    </template>
                </van-field>
                <div style="margin: 16px;">
                    <van-button round block type="primary" native-type="submit">保存</van-button>
                </div>
            </van-form>
        </van-popup>
    </div>
</template>

<style lang="scss" scoped>
.patient {
    position: relative;
    height: 100%;
    padding: 60px 15px 15px 15px;

    .patient-change {
        padding: 15px;

        > h3 {
            font-weight: normal;
            margin-bottom: 5px;
        }

        > p {
            color: var(--cp-text3);
        }
    }


    :deep(.van-cell__title) {
        display: flex;
        justify-content: start;
        align-items: center;
    }
}
</style>
